package com.eii.excel.util;

import com.eii.common.utils.StringUtils;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DictFormatUtil {

    /**
     * 缓存 key:name, value:HashBiMap<String,String>双向Map
     */
    private static final Map<String, HashBiMap<String, String>> reverseExpCache = new ConcurrentHashMap<>();

    /**
     * 解析导出值 0=男,1=女,2=未知
     *
     * @param propertyValue 参数值
     * @param converterExp  翻译注解
     * @param separator     分隔符
     * @return 解析后值
     */
    public static String convertByExp(String propertyValue, String converterExp, String separator) {
        HashBiMap<String, String> codeToName = getCacheMap(converterExp);
        //用code获取name
        return getMapValue(propertyValue, separator, codeToName);
    }

    /**
     * 反向解析值 男=0,女=1,未知=2
     *
     * @param propertyValue 参数值
     * @param converterExp  翻译注解
     * @param separator     分隔符
     * @return 解析后值
     */
    public static String reverseByExp(String propertyValue, String converterExp, String separator) {
        //用name获取code
        BiMap<String, String> nameToCode = getCacheMap(converterExp).inverse();
        return getMapValue(propertyValue, separator, nameToCode);
    }

    /**
     * 从map中解析值
     *
     * @param propertyValue
     * @param separator
     * @param biMap
     * @return
     */
    private static String getMapValue(String propertyValue, String separator, BiMap<String, String> biMap) {
        if (StringUtils.containsAny(separator, propertyValue)) {
            StringBuilder propertyString = new StringBuilder();
            for (String value : propertyValue.split(separator)) {
                if (biMap.containsKey(value)) {
                    propertyString.append(biMap.get(value))
                            .append(separator);
                }
            }
            return StringUtils.strip(propertyString.toString(), separator);
        } else {
            return biMap.get(propertyValue);
        }
    }

    /**
     * 解析值Map对象
     *
     * @param converterExp
     * @return
     */
    private static HashBiMap<String, String> getCacheMap(String converterExp) {
        HashBiMap<String, String> strDictMap = reverseExpCache.get(converterExp);
        if (strDictMap == null) {
            strDictMap = HashBiMap.create();
            String[] convertSource = converterExp.split(",");
            for (String item : convertSource) {
                String[] itemArray = item.split("=");
                strDictMap.put(itemArray[0], itemArray[1]);
            }
            reverseExpCache.put(converterExp, strDictMap);
        }
        return strDictMap;
    }
}
